let {
  insertNewProject,
  insertContacts,
  getFWLB
} = require("../../../api/programs/follow");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    showfwlb: false,
    fwlbOptions: [],

    fieldNames: {
      text: "nr",
      value: "nr",
      children: "child",
    },
    fwlbValue: "",
    cascaderfwlb: "",
    djbs: 1,
    Organization: {
      "xmbh": "", //项目编号
      "fwsname": "",
      "fwsbh": "",
      "fwlb": "",
      sfrzqy: 0,
      "fwrname": "",
      "rybh": "",

      jglb: "企业组织",
      djbs: null
    },
    OrganizationPersen: {
      fwsname: '',
      fwsbh: '',
      xb: '男',
      nl: '',
      fwrname: '',
      rybh: '',
      phone: '',
      wxh: '',
      bm: '',
      zw: '',
      jg: '',
      cyn: '',
      zz: '',
      ywtc: '',
      byyx: ''
    },
    pickerShow: false,
    OrganizationType: ["政府机构", "企业组织", "非营利组织", "社会团体", "学校机构"],
  },

  onClickfwlb(e) {
    this.setData({
      showfwlb: true,
    });
  },
  onClose(e) { 
    this.setData({
      showfwlb: false,
    });
  },
  onChangefwlb(e) { },
  onFinishfwlb(e) {
    const {
      selectedOptions,
      value
    } = e.detail;
console.log(selectedOptions)
    const fwlbValue =value

    this.setData({
      fwlbValue,
      cascaderfwlb: value,
      "Organization.fwlb":value
    });
    this.onClose()
  },
  onConfirm(e) {
    const {
      picker,
      value,
      index
    } = e.detail;

    this.setData({
      'Organization.jglb': value
    })
    this.onCancel()
  },
  openPick() {
    this.setData({
      pickerShow: true
    })
  },
  onCancel() {
    this.setData({
      pickerShow: false
    })
  },
  inputValue(e) {
    const param = e.currentTarget.dataset.name; //字段名
    const value = e.detail; //值
    const key = `Organization.${param}`;

    this.setData({
      [key]: value,
      // [msg]:'' //清空错误提示
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    getFWLB().then(res => {
      this.setData({
        djbs: options.djbs,
        fwlbOptions: res.data
      })
  
    })

    let timestamp = Date.parse(new Date());
    let date = new Date(timestamp);
    //获取年份
    let Y = date.getFullYear();
    //获取月份
    let M =
      date.getMonth() + 1 < 10 ?
        "0" + (date.getMonth() + 1) :
        date.getMonth() + 1;

    let rand = "";
    for (let i = 0; i < 3; i++) {
      let r = Math.floor(Math.random() * 10);
      rand += r;
    }
    if (options.djbs == 1) {
      this.setData({
        Organization: {
          xmbh: options.xmbh, //项目编号
          fwsname: "",
          fwsbh: options.fwsbh ? options.fwsbh : `fws${Y}${M}${rand}`,
          fwrname: "",
          sfrzqy: 0,

          rybh: "",
          fwlb: '',
          jglb: "企业组织",
          djbs: options.djbs
        },
      });
    } else if (options.djbs == 2) {
      wx.setNavigationBarTitle({
        title: '对接方联系人'
      })
      console.log(options.xmbh)
      this.setData({
        'OrganizationPersen.xmbh': options.xmbh,

        'OrganizationPersen.fwsname': options.fwsname,
        'OrganizationPersen.fwsbh': options.fwsbh,
        'OrganizationPersen.rybh': `fwsr${Y}${M}${rand}`,

      })
    }
    else if (options.djbs == 3) {
      wx.setNavigationBarTitle({
        title: '对接方联系人'
      })
      
      this.setData({
        OrganizationPersen:{...JSON.parse(options.ryData)}
      })
    }


  },

  onPush() {
    try {
      if (this.data.djbs == 1) {
        console.log(this.data.Organization)
        if (this.data.Organization.xmbh === "" || this.data.Organization.jglb === ""  || this.data.Organization.fwsname === "" || this.data.Organization.fwsbh === "") {

          wx.showToast({
            title: "请填写必填项",
            icon: "error",
            duration: 2000, //持续的时间
          });
          return;
        }
        this.insertNewProject();
      } else {
        console.log(this.data.OrganizationPersen)

        if (this.data.OrganizationPersen.fwrname === "" || this.data.OrganizationPersen.phone === "") {

          wx.showToast({
            title: "请填写必填项",
            icon: "error",
            duration: 2000, //持续的时间
          });
          return;
        }
        this.insertNewProject();
      }
    } catch (error) {
      console.log(error);
    }
  },
  insertNewProject() {
    let time = new Date().getTime();
    //将时间戳格式转换成年月日时分秒
    let date = new Date(time);
    let bbTime = `${date.getFullYear()}-${date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1
      }-${date.getDate() < 10 ? "0" + date.getDate() : date.getDate()}`;
    let tjTime = `${date.getHours() < 10 ? "0" + date.getHours() : date.getHours()
      }:${date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()}:${date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()
      }`;
      let INFO = wx.getStorageSync("userInfoMy")

    this.setData({
      "Organization.tjsj": `${bbTime} ${tjTime}`,
      "Organization.tname":INFO.jname ,
      "OrganizationPersen.tjsj": `${bbTime} ${tjTime}`,
      "OrganizationPersen.tname":INFO.jname ,
    });
    if (this.data.djbs == 1) {
      insertNewProject(this.data.Organization).then((res) => {
        wx.showToast({
          title: "对接方添加完成",
          icon: "none",
        });
        setTimeout(() => {
          this.setData({
            showDialog: true
          });
          let pages = getCurrentPages();
          let prevPage = pages[pages.length - 2];
          wx.navigateBack({
            delta: -1,
            success: function (e) { // 成功的回调
              if (prevPage == undefined || prevPage == null) return;
              prevPage.getDetail();  // 调用A页面的方法, 并将值传过去
            }
          });
        }, 1000);
      })
    } else {
      insertContacts(this.data.OrganizationPersen).then((res) => {
       if(this.data.OrganizationPersen.jgID){
        wx.showToast({
          title: "对接方联系人修改完成",
          icon: "none",
        });
       }else{
        wx.showToast({
          title: "对接方联系人添加完成",
          icon: "none",
        });
       }
        setTimeout(() => {

          let pages = getCurrentPages();
          let prevPage = pages[pages.length - 2];
          wx.navigateBack({
            delta: -1,
            success: function (e) { // 成功的回调
              if (prevPage == undefined || prevPage == null) return;
              prevPage.getProjectMember();  // 调用A页面的方法, 并将值传过去
            }
          });
        }, 1000);
      })
    }
  },
  inputValue(e) {
    let param = e.currentTarget.dataset.name; //字段名
    let value = e.detail; //值

    let key = ''
    if (this.data.djbs == 1) {
      key = `Organization.${param}`;
    } else {
      key = `OrganizationPersen.${param}`;
    }
    // const msg=`checkData.${param}`;

    this.setData({
      [key]: value,
      // [msg]:'' //清空错误提示
    });
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { },
});